<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="4"
      :wrapperSpan="wrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="delegateScopeType" label="代理范围">
          <FISelect
            v-model="state.query.delegateScopeType"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'ALL', label: '全部代理' },
              { value: 'PROCESS', label: '流程代理' },
              { value: 'NODE', label: '活动代理' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="delegater" label="委托人">
          <FISelect
            v-model="state.query.delegater"
            valueCustom="loginName"
            :props="{ value: 'loginName', label: 'userCName' }"
            :options="allStarterArr"
            :display-key="['loginName', 'userCName']"
            filterable
            @select="
              (item) => {
                state.query.delegaterName = item.userCName
              }
            "
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="accepter" label="代理人">
          <FISelect
            v-model="state.query.accepter"
            valueCustom="loginName"
            :props="{ value: 'loginName', label: 'userCName' }"
            :options="allStarterArr"
            :display-key="['loginName', 'userCName']"
            filterable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="enableStatus" label="状态">
          <FISelect
            v-model="state.query.enableStatus"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'Running', label: '有效' },
              { value: 'Expired', label: '过期' },
              { value: 'Closed', label: '关闭' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      primaryKey="formId"
      v-model:columns="columns"
      deletable
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :show-save-model="false"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-delete="handleOperation('delete')"
    >
      <!-- 自定义列 moduleEname1 -->
      <template #manage="{ scope }">
        <FIButton border size="small">查看</FIButton>
        <FIButton border size="small">图形监控</FIButton>
      </template>
      <template #his="{ scope }">
        <FIButton border size="small">查看</FIButton>
      </template>
      <template #headerBtn>
        <FIButton id="add" border @click="handleAdd">新增</FIButton>
        <FIPopconfirmBtn
          class="margin-left12"
          title="您是否确认关闭选中数据吗？"
          beforePopText="请选择一条数据"
          buttonText="关闭"
          :btn-binds="{ id: 'close', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperation('close')"
        />
        <!-- <FIPopconfirmBtn
          class="margin-left12"
          title="您是否确认删除选中数据吗？"
          beforePopText="请选择一条数据"
          buttonText="删除"
          :btn-binds="{ id: 'delete', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperation('delete')"
        /> -->
        <!-- <el-button id="export" class="margin-left12" :loading="exportLoading" type="primary" @click="exportClick"
          >导出</el-button
        > -->
      </template>
    </FITable>
    <addModel
      :visible="showAddModel"
      :delegaterList="delegaterList"
      :accepterList="accepterList"
      @update:visible="(newValue) => (showAddModel = newValue)"
      @save-ok="searchFn('new')"
    />
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import addModel from './addModel.vue'
import FIInput from '@/components/FIInput.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIDatePicker from '@/components/FIDatePicker.vue'
import { apiQueryAllProcesses, apiQueryUser, apiQueryTask, apiQueryDept } from '@/api/modules/EWPT.js'
import { apiRequestPost, apiRequestExport } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
import LocalCache from '@/utils/cache'
// 路由对象
const route = useRoute()
// el-col span栅格占据的列数
const wrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'TaskDelegate'
const showAddModel = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    delegateScopeType: '', // 代理范围
    delegater: '', // 委托人id
    delegaterName: '', // 委托人名称
    accepter: '', // 受理人id
    // accepterName: '', // 受理人名称
    enableStatus: '', // 状态 Running:有效  Expired：过期 Closed：关闭,
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  {
    label: '代理范围',
    prop: 'delegateScopeType',
    align: 'center',
    width: '180',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'ALL', label: '全部代理' },
        { value: 'PROCESS', label: '流程代理' },
        { value: 'NODE', label: '活动代理' },
      ],
    },
  },
  {
    label: '代理流程',
    prop: 'processDefCode',
    align: 'center',
    width: '150',
  },
  {
    label: '代理类型',
    prop: 'delegateType',
    align: 'center',
    width: '120',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'USER', label: '按用户' },
        { value: 'ROLE', label: '按角色' },
        { value: 'DEPT', label: '按部门' },
      ],
    },
  },
  {
    label: '委托人部门',
    prop: 'delegateDept',
    align: 'center',
    width: '150',
  },
  {
    label: '委托角色',
    prop: 'delegateRoleCname',
    align: 'center',
    width: '150',
  },
  {
    label: '委托人',
    prop: 'delegater',
    align: 'center',
    width: '150',
  },
  {
    label: '受理人部门',
    prop: 'acceptDept',
    align: 'center',
    width: '150',
  },
  {
    label: '受理人角色',
    prop: 'acceptRole',
    align: 'center',
    width: '150',
  },
  {
    label: '受理人',
    prop: 'accepter',
    align: 'center',
    width: '150',
  },
  {
    label: '开始日期',
    prop: 'delegateStartDate',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '结束日期',
    prop: 'delegateEndDate',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '状态',
    prop: 'enableStatus',
    align: 'center',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'Closed', label: '关闭' },
        { value: 'Running', label: '有效' },
      ],
    },
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}

// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  if (type == 'new') {
    pageConfig.currentPage = 1
  }
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}

// 关闭、删除函数
const handleOperation = (type: string) => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []

  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      let obj = {
        deputyId: item.deputyId,
      }
      ids.push(obj)
    })
  isTableLoading.value = true

  // const apiUrl =
  //   type === 'close' ? '/bpm-service/TaskDelegate/closeDelegation' : '/bpm-service/TaskDelegate/deleteDelegation'
  const apiUrl = type === 'close' ? proxy.$Button_api('close', route.name) : proxy.$Button_api('delete', route.name)
  console.log('------2222', apiUrl, ids)

  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      useMessage().success(type === 'close' ? '关闭成功' : '删除成功')
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const handleAdd = () => {
  showAddModel.value = true
}

//导出
const exportLoading = ref(false)
const exportClick = () => {
  exportLoading.value = true
  const apiUrl = proxy.$Button_api('export', route.name)
  apiRequestExport(apiUrl, state.query)
    .then(() => {
      exportLoading.value = false
      useMessage().success('导出成功')
    })
    .catch(() => {
      exportLoading.value = false
    })
}
// 所有流程
const allProcessesArr = ref([])
// 查询所有流程
const getAllProcesses = () => {
  apiQueryAllProcesses().then((res) => {
    if (res.data.success === true) {
      allProcessesArr.value = res.data.data || []
    }
  })
}
// 所有任务名称
const allTaskArr = ref([])
// 查询所有流程
const getAllTask = () => {
  apiQueryTask().then((res) => {
    if (res.data.success === true) {
      allTaskArr.value = res.data.data || []
    }
  })
}
// 流程发起人
const allStarterArr = ref([])
// 查询所有流程发起人
const getAllProcessesStarter = () => {
  apiQueryUser().then((res) => {
    if (res.data.success === true) {
      allStarterArr.value = res.data.data || []
    }
  })
}
const userData = LocalCache.getCache('user')
const userId = userData.loginName
// 委托人
const delegaterList = ref([])
// 查询所有流程发起人
const getDelegaterList = () => {
  const obj = {
    current: 1,
    size: 999,
  }
  apiRequestPost('/bpm-service/BpmUser/queryUserdelegater', obj).then((res) => {
    console.log('-----1111', res)
    if (res.data.success === true) {
      console.log('-----1111', res.data.data.result)
      delegaterList.value = res.data.data.result || []
    }
  })
}
// 受理人
const accepterList = ref([])
// 查询所有流程发起人
const getAccepterList = () => {
  const obj = {
    current: 1,
    size: 999,
  }
  apiRequestPost('/bpm-service/BpmUser/queryUserAccept', obj).then((res) => {
    console.log('-----', res)
    if (res.data.success === true) {
      accepterList.value = res.data.data.result || []
    }
  })
}
onMounted(() => {
  getAllProcesses()
  getAllTask()
  getAllProcessesStarter()
  getDelegaterList()
  getAccepterList()
  // 获取查询条件缓存
  const { cachedQuery } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  searchFn()
})
</script>
<style lang="less" scoped></style>
